package com.logic.utils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.pjc.annotation.Protocol;
import com.pjc.annotation.SrvToSrv;
import com.pjc.utils.ClassUtils;
import com.pjc.utils.ConfigUtil;

/**
 * 逻辑服务器缓存类
 * 
 * @author 王畅
 * @version 创建时间：2015-6-18 下午04:55:18
 */
public class LogicSrvUtils {

	private static final Logger log = LoggerFactory.getLogger(LogicSrvUtils.class);

	public static int SERVER_ID = 1;
	private static LogicSrvUtils instance;
	private final ConcurrentHashMap<Integer, Method> methodMap = new ConcurrentHashMap<Integer, Method>();

	private LogicSrvUtils() {
	}

	public static LogicSrvUtils getInstance() {
		if (instance == null) {
			instance = new LogicSrvUtils();
		}
		return instance;

	}

	/**
	 * 启动协议扫描
	 * 
	 * @author 王畅
	 */
	public void setUp() {
		String packagePath = ConfigUtil.getInstance().getStringProperties("auto.scan.package");
		log.debug("扫描的包路径" + packagePath);
		Set<Class<?>> classes = ClassUtils.getClasses(Thread.currentThread().getContextClassLoader(), packagePath);
		ScanClassProtocolToMethodMapping(classes);
		SERVER_ID = ConfigUtil.getInstance().getIntProperties("server.id");
	}

	/**
	 * 扫描协议至缓存
	 * 
	 * @author 王畅
	 * @param classes
	 */
	private void ScanClassProtocolToMethodMapping(Set<Class<?>> classes) {
		if (classes == null || classes.size() == 0)
			return;
		for (Class<?> cla : classes) {
			Annotation anno = cla.getAnnotation(SrvToSrv.class);
			if (anno == null)
				continue;
			for (Method method : cla.getMethods()) {
				Annotation methodAnno = method.getAnnotation(Protocol.class);
				if (methodAnno == null)
					continue;
				Protocol protoAnno = (Protocol) methodAnno;
				int protoId = protoAnno.protoId();
				if (protoId == 0)
					continue;
				log.debug("protoId：" + protoId + ";Method：" + method.getName());
				methodMap.put(protoId, method);
			}
		}

	}

	/**
	 * 根据协议Id获取方法名
	 * 
	 * @author 王畅
	 * @param protoId
	 * @return
	 */
	public Method getMethod(int protoId) {
		return methodMap.get(protoId);
	}

}
